package window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * keyed 滚动窗口
 */
public class EventTimeTumblingWindowDemo {

    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Tuple3<Long, String, Long>> mapped = lines.map(new MapFunction<String, Tuple3<Long, String, Long>>() {
            @Override
            public Tuple3<Long, String, Long> map(String s) throws Exception {
                String[] fields = s.split(",");
                return Tuple3.of(Long.parseLong(fields[0]), fields[1], Long.parseLong(fields[2]));
            }
        });

        // watermark
        SingleOutputStreamOperator<Tuple3<Long, String, Long>> watermark = mapped.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple3<Long, String, Long>>(Time.seconds(2)) {
            @Override
            public long extractTimestamp(Tuple3<Long, String, Long> tuple) {
                return tuple.f0;
            }
        });
        // map
        SingleOutputStreamOperator<Tuple2<String, Long>> wordAndCnt = watermark.map(new MapFunction<Tuple3<Long, String, Long>, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(Tuple3<Long, String, Long> tuple3) throws Exception {
                return Tuple2.of(tuple3.f1, tuple3.f2);
            }
        });

        // keyed and window
        WindowedStream<Tuple2<String, Long>, String, TimeWindow> window = wordAndCnt.keyBy(t -> t.f0).window(TumblingEventTimeWindows.of(Time.seconds(5)));

        // apply
        SingleOutputStreamOperator<Tuple2<String, Long>> summed = window.sum(1);

        // sink
        summed.print();

        env.execute("tumbling window");
    }
}
